<template>
  <view class="fix-top-window">
    <view class="uni-header">
      <uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
      <view class="uni-group">
        <uni-easyinput type="text" v-model="query.description" :placeholder="$t('common.placeholder.query')" />
        <button class="uni-button hide-on-phone" type="default" size="mini" @click="getData(1)">{{$t('common.button.search')}}</button>
        <button class="uni-button" type="primary" size="mini" @click="navigateTo('./edit')"
        v-if="uniIDHasPermission('wia')">
          {{$t('common.button.batchAdd')}}
        </button>
        <button class="uni-button" size="mini" type="warn" v-if="uniIDHasPermission('wid')" 
		:disabled="!tableData.selectedIndexArray.length" @click="removeDataByIds()">{{ $t('common.button.batchDelete') }}</button>
        <!-- #ifdef H5 -->
          <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcel.data"
            :type="exportExcel.type" :name="exportExcel.filename">
            <button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
          </download-excel>
        <!-- #endif -->
      </view>
    </view>
    <view class="uni-container">
      <uni-table ref="tableRef" :emptyText="$t('common.empty')" border stripe
        type="selection" @selection-change="selectionChange">
        <uni-tr>
		  <uni-th align="center" filter-type="select" :filter-data="classifyOptions" width="80"
		    @filter-change="filterChange($event, 'classid')">分类</uni-th>
          <uni-th align="center" width="150">壁纸图片</uni-th>
		  <uni-th align="center" filter-type="select" :filter-data="getDictByType('RecommendType').options"
			@filter-change="filterChange($event, 'recommendLevel')"  width="100">推荐级别</uni-th>
          <uni-th align="center" filter-type="search" width="100"
            @filter-change="filterChange($event, 'description')">描述</uni-th>
		  <uni-th align="center" width="100">标签</uni-th>
          <uni-th align="center" width="80">评分</uni-th>
          <uni-th align="center" width="100">上传者</uni-th>
          <uni-th align="center" filter-type="timestamp" sortable width="100"
            @filter-change="filterChange($event, 'updateTime')">创建时间</uni-th>
          <uni-th align="center" width="80">审核状态</uni-th>
          <uni-th align="center" width="180">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item,index) in tableData.list" :key="index">
          <uni-td align="center">{{item.classiname}}</uni-td>
		  <uni-td align="center">
            <image :src="cloudIdToUrl(item.picurl,{h:178,w:100})" mode="aspectFill" @click="previewImage(item.picurl,'picurl')"
            style="width: 100px; height: 178px; border-radius: 5px; overflow: hidden;"></image>
          </uni-td>
		  <uni-td align="center">{{getDictText('RecommendType',item.recommendLevel)}}</uni-td>
          <uni-td align="center">{{item.description}}</uni-td>
          <uni-td align="center">
            <uni-tag v-for="(tag, tagIndex) in item.tabs" :key="tagIndex" :text="tag" type="primary" style="margin-right: 5px; margin-bottom: 5px;" />
          </uni-td>
          <uni-td align="center">{{item.score}}</uni-td>
          <uni-td align="center">{{item.nickname}}</uni-td>
          <uni-td align="center"><uni-dateformat :date="item.updateTime" format="yyyy-MM-dd"></uni-dateformat></uni-td>
          <uni-td align="center">
            <switch v-if="uniIDHasPermission('wie')" :checked='item.status' style="transform:scale(0.7)" @change="toggleFieldChange(item._id, 'status')"/>
            <uni-tag v-else inverted="true" :text="item.status? '已审核':'待审核'" :type="item.status?'success':'error'" />
          </uni-td>
          <uni-td align="center">
            <view class="uni-group">
              <button class="uni-button" size="mini"type="primary" 
              v-if="uniIDHasPermission('wie')" @click="navigateTo('./edit?id='+item._id, false)">
              {{ $t('common.button.edit') }}
            </button>
              <button class="uni-button" size="mini" type="warn" v-if="uniIDHasPermission('wid')" @click="removeDataByIds([item._id])">{{ $t('common.button.delete') }}</button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <view class="uni-pagination-box">
        <uni-pagination show-iconn show-page-size :page-size="query.pageSize" v-model="query.page"
          :total="tableData.total" @change="onPageChange" @pageSizeChange="changeSize" />
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { useTableSearch } from '@/utils/composable.js'
  import { cloudIdToUrl, formatDateTime } from '@/utils/common.js'
  const tableRef = ref(null)
  const wallpaperObj = uniCloud.importObject('iss-wallpaper')
  
  // 导出Excel的字段定义
  const exportExcel = ref({
    "filename": "iss-wallpaper-image.xls",
    "type": "xls",
    "fields": {
      "描述": "description",
      "分类": "classiname",
      "标签": "tabs",
      "评分": "score",
      "上传者": "nickname",
      "创建时间": "updateTime",
      "审核状态": "status"
    },
    "data":[]
  })
  
  // 数据字典定义
  const dictsRef = ref([{type:'RecommendType'}])
  
  // 分类选项
  const classifyOptions = ref([])
  // 加载分类选项
  const loadClassifyOptions = async () => {
    try {
      const res = await wallpaperObj.getList_classify({pageSize: 100})
      if (res.code === 200) {
          classifyOptions.value = res.data.list.map(item => ({
          text: item.name,
          value: item._id
        }))
      }
    } catch (e) {
      console.error('加载分类选项失败:', e)
    }
  }
  
  // 使用通用表格搜索逻辑
  const {
    query, // 查询条件 ref对象
    tableData, // 列表数据集合 ref对象
    getData, // 获取列表数据 method
    removeDataByIds, // 根据选择删除记录
    toggleFieldChange, // 列表中某条记录状态变化事件 method
    selectionChange, // 列表选中记录变化 method
    onPageChange, // table当前页变化事件 method
    changeSize, // table每页显示条数变化事件 method
    filterChange, // table 某列筛选条件变化
    sortChange, // table 某列排序变化
    previewImage, // 列表图片预览
    navigateTo, // 调整页面，并建立返回刷新数据的通信机制
	getDictByType, // 根据type获得字典对象
	getDictText, // 获取列表中对应数据字典的文本
  } = useTableSearch({
    title: '壁纸图片',
    tableRef,
	dictsRef,
    searchform: {
      description: '',
	  recommendLevel: '',
      classid: '',
      status: undefined,
      updateTime: []
    },
    getList: wallpaperObj.getList_image,
    columnToggle: wallpaperObj.columnToggle_image,
    remove: wallpaperObj.remove_image,
    onGetDataSucceed: (data)=>{
		// 更改联表查询的数据格式
		tableData.value.list = data.list.map(item => {
			// 创建一个新对象，包含原对象的所有属性
			const newItem = {
				...item,
				// 提取classid数组中的_id作为新的classid
				classid: item.classid[0]._id,
				// 添加classiname字段，值为classid数组中第一个元素的name
				classiname: item.classid[0].name
			};
			return newItem;
		})
	  
      // 当列表获得数据后，针对导出数据还是要做一些处理
      exportExcel.value.data = tableData.value.list.map(item => {
        // 创建一个新的对象，避免直接修改原对象
        const newItem = {...item}
        // 组合成 yyyy-MM-dd 格式
        newItem.createTime = formatDateTime(item.createTime)
        newItem.tabs = item.tabs ? item.tabs.join(',') : ''
        newItem.status = item.status ? '已审核' : '待审核'
        return newItem
      })
    }
  })

  
  onMounted(() => {
    loadClassifyOptions()
  })
</script>

<style scoped lang="scss">
.uni-tag {
  display: inline-block;
}
/* 解决 uni-app uni-table 横向滚动条导致左侧边框高度异常问题 */
::v-deep .table--border {
  border: none;
}

::v-deep .uni-table {
  border: 1px solid #ebeef5;
  border-right: none;
  border-bottom: none;
}

::v-deep .uni-table-th, 
::v-deep .uni-table-td {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>